﻿<%@ WebHandler Language="C#" Class="ContractApply" %>

using System;
using System.Web;
using Chenxin.Lib.Utility;
using System.Collections.Generic;
using Chenxin.Lib.Business.BLL;

/// <summary>
/// 业绩申请业务逻辑处理对象。
/// 处理业绩申请模块中相应的请求逻辑
/// owner：kimi
/// add time：2010.10.29
/// </summary>
public class ContractApply : AjaxHandlerBase {

    public ContractApply()
    {
        //添加业绩业绩申请
        htTypePermit.Add("add", Constants.Permit_AddContractApplyInfo);
        //修改业绩业绩申请
        htTypePermit.Add("edit", Constants.Permit_UpdateContractApplyInfo);
        //确认业绩申请
        htTypePermit.Add("confirm", Constants.Permit_ConfirmContractApplyInfo);
        //删除业绩申请
        htTypePermit.Add("del", Constants.Permit_DelContractApplyInfo);
        //修改成交记录
        htTypePermit.Add("confirmedit", Constants.Permit_Bargain_Edit);
        //导出
        htTypePermit.Add("export", Constants.Permit_ExportContractApplyInfo_All);
    }

    public override void RequestProcess(HttpContext context)
    {
        try
        {
            context.Response.ContentType = "text/plain";
            context.Response.AddHeader("pragma", "no-cache");
            context.Response.AddHeader("cache-control", "");
            context.Response.CacheControl = "no-cache";

            string strOp = context.Request["op"];
            string strRet = string.Empty;
            switch (strOp.ToLower())
            {
                //添加业绩申请
                case "add":
                    strRet = AddApplyInfo(context);
                    break;
                //更新主营业务信息
                case "edit":
                    strRet = UpdateApplyInfo(context);
                    break;
                //备案列表
                case "getmarkedls":
                    strRet = getMarkList(context);
                    break;
                //获取店长，区经等
                case "getparents":
                    strRet = getParents(context);
                    break;
                //获取标准佣金
                case "getstandcomm":
                    strRet = getStandardCommission(context);
                    break;
                //获取初始信息
                case "getinitdata":
                    strRet = GetInitData(context);
                    break;
                //确认业绩申请 edit by kimi 2010.10.30
                case "confirm":
                    strRet = ConfirmApply(context);
                    break;
                //得到钥匙列表
                case "getkeylist":
                    strRet = getKeyList(context);
                    break;
                //获取申请列表
                case"getlist":
                    strRet = getApplist(context);
                    break;
                case"del":
                    strRet = deleteAppInfo(context);
                    break;
                //获取零散业务初始化数据
                case "getlooseinitdata":
                    strRet = GetLooseInitData(context);
                    break;
                //得到楼盘字典
                case "loadcommunity":
                    LoadCommunity(context);
                    break;
                    //获取其他业务初始化数据
                case "getotherinitdata":
                    strRet = GetLooseInitData(context);
                    break;
                //获取修改成交记录的初始化信息
                case "getconfirminitdata":
                    strRet = GetConfirmInitData(context);
                    break;
                //修改成交记录
                case "confirmedit":
                    strRet = UpdateContractInfo(context);
                    break;
                    //获取固定折让
                case "getfixdiscount":
                    strRet = GetFixDiscount(context);
                    break;
                default:
                    break;
            }
            context.Response.Write(strRet);
        }
        catch (Exception ex)
        {
            context.Response.Write(retExecResult(Constants.ExecResult.Error, ex.Message, ""));
        }
    }
    
    //获取固定折让
    private string GetFixDiscount(HttpContext context)
    {
        try
        {
            string companyid = context.Request["CompanyId"];
            string type = context.Request["type"];
            string strSql = string.Format("select isnull(ParaValue,'0') from t_Company_BusinessParam where CompanyId='{0}' and ParaType={1} ", companyid, type);
            string scalar = Chenxin.Lib.Business.DAL.v_Contract_CommisionDetailInfo.GetScalar(strSql);
            if (string.IsNullOrEmpty(scalar))
                scalar = "0";
            return string.Format("{{success:'1',msg:'',data:{0}}}", scalar);            
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }

    private string UpdateContractInfo(HttpContext context)
    {
        try
        {
            string strMainBusiness = context.Request.Params["model"].ToString();
            string strPointInfo = context.Request.Params["PointInfo"].ToString();
            if (strMainBusiness == string.Empty)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Msg_Confirm_ERRO_NO_MAININFO);
            if (strPointInfo == string.Empty)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Msg_Confirm_ERRO_NO_MAININFO);

            //成交记录实体类
            Chenxin.Lib.Business.Entity.t_Contract_BaseInfo model = (Chenxin.Lib.Business.Entity.t_Contract_BaseInfo)JsonHelp.Convert2Entity(strMainBusiness, typeof(Chenxin.Lib.Business.Entity.t_Contract_BaseInfo));
            if (model.BusinessType != 10)
                model.FixDiscount = 0;
            
            //点数分配列表
            List<Chenxin.Lib.Business.Entity.t_Contract_PointAllotInfo> lsPointInfo = (List<Chenxin.Lib.Business.Entity.t_Contract_PointAllotInfo>)JsonHelp.Convert2Entity(strPointInfo, typeof(List<Chenxin.Lib.Business.Entity.t_Contract_PointAllotInfo>));

            //设定实体类初始值
            model = addEntity(model);
            
            if (model.LockStatus ==255 && model.bArchivement)
                return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Global_Err_Exception + ":" + "该成交记录已生成业绩且处于封帐状态，不允许修改！");

            model.LockStatus = (model.bArchivement) ? 255 : model.LockStatus;
            
            //保存成交信息
            Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.Update(model);
            
            //保存点数分配信息
            Chenxin.Lib.Business.DAL.t_Contract_PointAllotInfo.DeletePoint(model.ContractId);
            
            for (int i = 0; i < lsPointInfo.Count; i++)
            {
                lsPointInfo[i].RecordId = Guid.NewGuid();
                lsPointInfo[i].ContractId = model.ContractId;
                lsPointInfo[i].CreateTime = DateTime.Now;
                Chenxin.Lib.Business.DAL.t_Contract_PointAllotInfo.Add(lsPointInfo[i]);
            }

            //更新佣金实收抵扣情况
            string strMessage = "";
            if (model.bArchivement) Chenxin.Lib.Business.BLL.ContractBaseInfo.CaculateFinanceDeductInfo(model.ContractId, out strMessage);
            
            //保存上下家客户信息
            string strOutMessage = "";
            if (!Chenxin.Lib.Business.BLL.ContractBaseInfo.AddContractCustomerInfo(model, out strOutMessage))
                return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Global_Err_Exception + ":" + strOutMessage);

            //保存成交佣金信息
            if (!Chenxin.Lib.Business.BLL.ContractBaseInfo.UpdateContractCommissionInfo(model, out strOutMessage))
                return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Global_Err_Exception + ":" + strOutMessage);
             
            /*
            if (model.BusinessType == 10 || model.BusinessType == 20)
            {
                //保存新业主信息
                Chenxin.Lib.Business.BLL.ContractBaseInfo.AddHouseNewOwnerInfo(model, out strOutMessage);
                //return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Global_Err_Exception + ":" + strOutMessage);
                
                //保存房源更新信息
                Chenxin.Lib.Business.BLL.ContractBaseInfo.UpdateHouseInfo(model, out strOutMessage);
                    //return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Global_Err_Exception + ":" + strOutMessage);               
            }

            //添加跟单记录
            Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
            house_TraceInfo.TraceType = 0;
            house_TraceInfo.TraceContext = model.ConfirmEmplyee + "修改了" +
                model.BuyerUserName + "的" + (model.BusinessType == 10 ? "买卖" : "租赁") + "成交记录。" +
                "编号：" + model.ContractCode;

            house_TraceInfo.HouseId = model.HouseId;
            house_TraceInfo.HouseCode = model.HouseCode;
            house_TraceInfo.HouseAddress = model.HouseAddress;
            house_TraceInfo.status = 0;
            house_TraceInfo.OprDepart = model.BuyerDepartName;
            house_TraceInfo.OprDepartId = model.BuyerDepartId;
            house_TraceInfo.OprPerson = model.BuyerUserName;
            house_TraceInfo.OprPersonId = model.BuyerUserId;
            AddTrace(house_TraceInfo);

            //添加日志
            Chenxin.Lib.House.Entity.House_UserLogs userLogs = new Chenxin.Lib.House.Entity.House_UserLogs();
            userLogs.RecordId = Guid.NewGuid();
            userLogs.UserId = CurrentUserInfo.UserId;
            userLogs.UserName = CurrentUserInfo.UserName;
            userLogs.DepartId = CurrentUserInfo.DepartId;
            userLogs.DepartName = CurrentUserInfo.DepartName;
            userLogs.OperationContext = model.ConfirmEmplyee + "修改" +
                model.BuyerUserName + "的" + (model.BusinessType == 10 ? "买卖" : "租赁") + "成交记录。" +
                "编号：" + model.ContractCode;
            userLogs.OprType = "确认成交编号";
            userLogs.Addtime = DateTime.Now;
            userLogs.Id = model.HouseId;
            Chenxin.Lib.House.DAL.House_UserLogs.Add(userLogs);
             */

            string text = string.Empty;
            text = CurrentUserInfo.UserName + "：修改了成交记录。成交编号：" + model.ContractCode;
            AddLog(text, BusinessType.BusinessTypeComboList()["OprType_UpdContractInfo"].ToString());
            
            return string.Format("{{success:'1',msg:'{0}',data:''}}", "成交记录修改成功！");
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }
    
    /// <summary>
    /// 获取主营业绩修改时的初始化数据
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetConfirmInitData(HttpContext context)
    {
        try
        {
            string modelid = context.Request.Params["modelid"];
            Chenxin.Lib.Business.Entity.t_Contract_BaseInfo contractBaseInfo =
                Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(new Guid(modelid));
            if (contractBaseInfo == null)
            {
                return string.Format("{{success:'0',msg:'{0}',data:''}}", Resources.Message.Err_Contract_ApplyInfo_getModel);
            }

            System.Data.DataSet ds = Chenxin.Lib.Business.DAL.t_Contract_PointAllotInfo.GetList(string.Format(" ContractId='{0}'", contractBaseInfo.ContractId));

            return string.Format("{{success:'1',msg:'{0}',data:{{applyInfo:{1},pointList:{{count:{2},{3}}}}}}}",
                Resources.Message.Global_Msg_SUCCESS,
                Chenxin.Lib.Utility.JsonHelp.Convert2Json(contractBaseInfo), ds.Tables[0].Rows.Count,
                Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0]));
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }
    
    //-----------------------------------零散---------------------------------------------------
    /// <summary>
    /// 根据拼音字母或者文字，查询符合条件的楼盘
    /// </summary>
    /// <param name="context"></param>
    private void LoadCommunity(HttpContext context)
    {
        Guid departId = CurrentUserInfo.DepartId;
        string strCachKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPART_SETTINGS, departId);
        Chenxin.Lib.House.Entity.House_BusinessSetting setting = null;

        Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
        setting = cs.GetObject<Chenxin.Lib.House.Entity.House_BusinessSetting>(strCachKey);
        if (!cs.Hit)
        {
            setting = Chenxin.Lib.House.DAL.House_BusinessSetting.GetModel(departId);
            if (setting != null) cs.Set(strCachKey, setting);
        }

        string strCitys = "";

        if (setting != null)
        {
            if (!string.IsNullOrEmpty(setting.CanAddAtCityId)) strCitys = setting.CanAddAtCityId;
        }

        if (strCitys == "") strCitys = CurrentUserInfo.CityId.ToString();

        System.Text.StringBuilder sbwhere = new System.Text.StringBuilder();

        string[] aryCity = strCitys.Split(new char[] { ',' });
        foreach (string strCityId in aryCity)
        {
            if (string.IsNullOrEmpty(strCityId)) continue;
            if (sbwhere.Length == 0)
                sbwhere.AppendFormat("((CityId = '{0}')", strCityId);
            else
                sbwhere.AppendFormat(" OR (CityId = '{0}')", strCityId);
        }
        if (sbwhere.Length > 0) sbwhere.Append(")");

        if (sbwhere.Length > 0)
            sbwhere.Append(" AND (Status=1) ");
        else
            sbwhere.Append(" (Status=1) ");

        if (context.Request["query"] != null)
        {
            sbwhere.AppendFormat(" AND (CommunityName like '%{0}%' OR Py like '%{0}%') ", context.Request["query"]);

            System.Data.DataTable dt = Chenxin.Lib.House.DAL.Community_BaseInfo.GetList(sbwhere.ToString(), "CommunityName desc", 30).Tables[0];

            System.Text.StringBuilder sugestionSb = new System.Text.StringBuilder();

            foreach (System.Data.DataRow dr in dt.Rows)
            {
                sugestionSb.AppendFormat("'{0}',", dr["CommunityName"]);
            }
            context.Response.Write(string.Format("{{query:'{0}',suggestions:[{1}],{2}}}", context.Request["query"], sugestionSb.Length > 0 ? sugestionSb.Remove(sugestionSb.Length - 1, 1).ToString() : sugestionSb.ToString(), JsonHelp.Convert2Json(dt).Replace("\"rows\"", "data")));
        }
    }

    
    /// <summary>
    /// 获取初始化数据
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetLooseInitData(HttpContext context)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        string modelId = context.Request["modelid"];


        if (!string.IsNullOrEmpty(modelId))
        {
            Chenxin.Lib.Business.Entity.ContractApplyInfo entInfo = Chenxin.Lib.Business.BLL.ContractApplyInfo.GetModel(new Guid(modelId));


            //点数业务类
            System.Data.DataSet ds = Chenxin.Lib.Business.BLL.ApplyPointAllot.GetList(string.Format("ContractId = '{0}'", modelId));

            sb.AppendFormat("applyInfo:{0},pointList:{{count:{1},{2}}},", JsonHelp.Convert2Json(entInfo), ds.Tables[0].Rows.Count, JsonHelp.Convert2Json(ds.Tables[0]));
        }
        sb.AppendFormat("userInfo:{0}", JsonHelp.Convert2Json(CurrentUserInfo));

        return string.Format("{{success:1,msg:'',data:{{{0}}}}}", sb.ToString());
    }
    //-----------------------------------主营---------------------------------------------------

    /// <summary>
    /// 删除业绩申请
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string deleteAppInfo(HttpContext context)
    {
        try
        {
            string RecordId = context.Request["modelid"];
            Chenxin.Lib.Business.Entity.ContractApplyInfo model = Chenxin.Lib.Business.DAL.ContractApplyInfo.GetModel(new Guid(RecordId));
            //ConfirmType(已确认1，未确认0)
            if (model.ConfirmType.Equals(0))
            {
                //删除其关联子表中数据
                if (Chenxin.Lib.Business.BLL.ContractApplyInfo.DeleteApplyPointAllot(model.RecordId))
                {
                    //删除业绩申请 
                    Chenxin.Lib.Business.BLL.ContractApplyInfo.Delete(new Guid(RecordId));
                }

                string text = string.Empty;
                switch (model.BusinessType)
                {
                    case 10:
                        text = CurrentUserInfo.UserName + "：删除买卖业绩申请。房源：[" + model.HouseCode + "]" + model.HouseAddress;
                        AddLog(text, BusinessType.BusinessTypeComboList()["OprType_M_DelApply"].ToString());
                        break;
                    case 20:
                        text = CurrentUserInfo.UserName + "：删除租赁业绩申请。房源：[" + model.HouseCode + "]" + model.HouseAddress;
                        AddLog(text, BusinessType.BusinessTypeComboList()["OprType_Z_DelApply"].ToString());
                        break;
                    case 30:
                        text = CurrentUserInfo.UserName + "：删除零散业绩申请。房源：[" + model.Community + "]" + model.HouseAddress;
                        AddLog(text, BusinessType.BusinessTypeComboList()["OprType_L_DelApply"].ToString());
                        break;
                    case 40:
                        text = CurrentUserInfo.UserName + "：删除其他业绩申请。业务描述：" + model.BusinessDescribe;
                        AddLog(text, BusinessType.BusinessTypeComboList()["OprType_Q_DelApply"].ToString());
                        break;
                }
                
                return string.Format("{{success:'1',msg:'{0}',data:''}}", Resources.Message.Msg_Delete_Success);
            }
            else
            {
                return string.Format("{{success:'0',msg:'{0}{1}',data:''}}", Resources.Message.Global_Err_FAIL, "已确认的业绩不能删除！");
            }
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }        
    }
    /// <summary>
    /// 获取业绩申请列表
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string getApplist(HttpContext context)
    {
        try
        {
            //页码
            int strPageIndex = (string.IsNullOrEmpty(context.Request["pageindex"])) ? 1 : int.Parse(context.Request["pageindex"]) + 1;
            //页显示行数
            int strPageSize = (string.IsNullOrEmpty(context.Request["pagesize"])) ? 30 : int.Parse(context.Request["pagesize"]);
            //查询条件
            string sqlWhere = GenerateCondition(context);
            //查询分页信息
            System.Data.DataSet ds = Chenxin.Lib.Business.BLL.ContractApplyInfo.getList(strPageIndex, strPageSize, sqlWhere);
            //总页数
            int count = (int)ds.Tables[1].Rows[0][0];
            string head = "";

            switch (context.Request["showtype"].ToString())
            {
                //主营业务
                case "10":
                    head = "columns.mainHead";
                    break;
                case "20":
                    head = "columns.mainHead";
                    break;
                //零散业务
                case "30":
                    head = "columns.subHead";
                    break;
                //其他业务
                case "40":
                    head = "columns.otherHead";
                    break;
                //默认主营业务
                default:
                    break;
            }

            return string.Format("{{success:1,msg:'',data:{{count:{0},head:{1},{2}}}}}", count, head, JsonHelp.Convert2Json(ds.Tables[0]));

        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }
    
    /// <summary>
    /// 拼接查询条件
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public string GenerateCondition(HttpContext context)
    {
        try
        {
            //获取页面查询条件
            Guid city = (string.IsNullOrEmpty(context.Request["cityid"])) ? Guid.Empty : new Guid(context.Request["cityid"]);
            Guid company = (string.IsNullOrEmpty(context.Request["companyid"])) ? Guid.Empty : new Guid(context.Request["companyid"]);
            Guid businessdistrict = (string.IsNullOrEmpty(context.Request["areaid"])) ? Guid.Empty : new Guid(context.Request["areaid"]);
            Guid departs = (string.IsNullOrEmpty(context.Request["departid"])) ? Guid.Empty : new Guid(context.Request["departid"]);
            Guid employee = (string.IsNullOrEmpty(context.Request["userid"])) ? Guid.Empty : new Guid(context.Request["userid"]);

            string applytime = context.Request.QueryString["applytime"];
            string starttime = context.Request.QueryString["starttime"];
            string endtime = context.Request.QueryString["endtime"];
            string keyword = context.Request.QueryString["keyword"];
            string businesstype = context.Request.QueryString["BusinessType"];
            string confirmtype = context.Request.QueryString["ConfirmType"];

            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            //判断级联菜单
            if (employee != Guid.Empty)
                sb.AppendFormat(" AND (VenderUserId = '{0}' or BuyerUserId ='{0}' or (RecordId in (select contractid from t_Apply_Point_Allot where EmployeeId='{0}'))) ", employee);
            else if (departs != Guid.Empty)
                sb.AppendFormat(" AND (VenderDepartId = '{0}' or BuyerDepartId ='{0}' or (RecordId in (select contractid from t_Apply_Point_Allot where DepartId='{0}')))", departs);
            else if (businessdistrict != Guid.Empty)
            {
                sb.AppendFormat(" and ((VenderDepartId in (Select ChildId from v_Hr_Struct_DepartTreeRelation where ParentId = '{0}')) or "
                   + "(BuyerDepartId in (Select ChildId from v_Hr_Struct_DepartTreeRelation where ParentId = '{0}')) or "
                   + "(RecordId in (select contractid from t_Apply_Point_Allot where DepartId in " +
                   "(Select ChildId from v_Hr_Struct_DepartTreeRelation where ParentId = '{0}'))))", businessdistrict);
            }
            else if (company != Guid.Empty)
                sb.AppendFormat(" and BuyerCompanyId = '{0}'", company);
            else if (city != Guid.Empty)
                sb.AppendFormat(" and BuyerCityId = '{0}'", city);
            else
                sb.AppendFormat(" and BuyerCompanyId = '{0}'", CurrentUserInfo.CompanyId);

            //查询权限判断权限
            System.Text.StringBuilder sb1 = new System.Text.StringBuilder();
            if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewContractApplyInfo_All))
            {
                sb1.Append(" (1=1) ");
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewContractApplyInfo_City))
            {
                sb1.AppendFormat(" (BuyerCityId = '{0}')", CurrentUserInfo.CityId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewContractApplyInfo_Company))
            {
                sb1.AppendFormat(" (BuyerCompanyId = '{0}')", CurrentUserInfo.CompanyId);
            }
            else if (CurrentUserInfo.ContainsPermit(Constants.Permit_ViewContractApplyInfo_Department))
            {
                sb1.AppendFormat(" (EXISTS(Select 1 from t_Business_EmpSetting M WHERE t_Contract_ApplyInfo.VenderDepartId=M.DepartId And M.Userid= '{0}' and SearchContractApply=1)", CurrentUserInfo.UserId.ToString());
                sb1.AppendFormat(" or EXISTS(Select 1 from t_Business_EmpSetting M WHERE t_Contract_ApplyInfo.BuyerDepartId=M.DepartId And M.Userid= '{0}' and SearchContractApply=1)", CurrentUserInfo.UserId.ToString());
                sb1.AppendFormat(" or RecordId in (Select ContractId from t_Apply_Point_Allot M WHERE EXISTS(select 1 from t_Business_EmpSetting N where M.DepartId=N.DepartId and N.Userid= '{0}' and SearchContractApply=1)))", CurrentUserInfo.UserId.ToString());
            }
            else
            {
                sb1.AppendFormat(" (VenderUserId = '{0}' or BuyerUserId ='{0}' or (RecordId in (select contractid from t_Apply_Point_Allot where EmployeeId='{0}')))", CurrentUserInfo.UserId);
            }

            if (!String.IsNullOrEmpty(sb.ToString()))
                sb1.Append(sb.ToString());

            if (!String.IsNullOrEmpty(starttime))
            {
                sb1.Append(string.Format(" and CreateTime >= '{0}'", (starttime)));
            }

            if (!String.IsNullOrEmpty(endtime))
            {
                sb1.Append(string.Format(" and CreateTime < '{0}'", DateTime.Parse(endtime).AddDays(1)));
            }

            if (!String.IsNullOrEmpty(confirmtype))
            {
                sb1.Append(string.Format(" and ConfirmType = {0}", (confirmtype)));
            }

            if (!String.IsNullOrEmpty(keyword))
            {
                sb1.Append(" and (HouseAddress LIKE '%" + keyword + "%') or (HouseCode like '%" + keyword + "%')");
            }

            if (!String.IsNullOrEmpty(context.Request["showtype"]))
            {
                switch (context.Request["showtype"])
                {
                    //主营业务(买卖,租赁)
                    case "10":
                        sb1.AppendFormat(" and BusinessType = {0}", 10);
                        break;
                    case "20":
                        sb1.AppendFormat(" and BusinessType = {0}", 20);
                        break;
                    //零散业务
                    case "30":
                        sb1.AppendFormat(" and BusinessType = {0}", 30);
                        break;
                    //其他业务
                    case "40":
                        sb1.AppendFormat(" and BusinessType = {0}", 40);
                        break;
                    //默认主营业务
                    default:
                        sb1.AppendFormat(" and BusinessType = {0}", 10);
                        break;
                }
            }
            return sb1.ToString();
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }
    /// <summary>
    /// 确认业绩申请
    /// add by kimi 2010.10.30
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string ConfirmApply(HttpContext context)
    {
        try
        {
            string strMainBusiness = context.Request.Params["model"].ToString();
            string strPointInfo = context.Request.Params["PointInfo"].ToString();
            if (strMainBusiness == string.Empty)
                return string.Format("{{success:'-1',msg:'{0}',data:''}}", Resources.Message.Msg_Confirm_ERRO_NO_MAININFO);
            if (strPointInfo == string.Empty)
                return string.Format("{{success:'-1',msg:'{0}',data:''}}", Resources.Message.Msg_Confirm_ERRO_NO_MAININFO);

            //成交记录实体类
            Chenxin.Lib.Business.Entity.t_Contract_BaseInfo model = (Chenxin.Lib.Business.Entity.t_Contract_BaseInfo)JsonHelp.Convert2Entity(strMainBusiness, typeof(Chenxin.Lib.Business.Entity.t_Contract_BaseInfo));
            if (model.BusinessType != 10)
                model.FixDiscount = 0;
            //
            Guid applyId = model.ApplyId;
            Chenxin.Lib.Business.Entity.ContractApplyInfo applyInfo = Chenxin.Lib.Business.BLL.ContractApplyInfo.GetModel(applyId);
            if (applyInfo == null) return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, "业绩申请信息丢失，请联系管理员！");

            if (applyInfo.Status == -1) return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, "业绩申请信息已作废，不能进行业绩确认！");
            if (applyInfo.ConfirmType==1) return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, "该业绩申请被确认！成交编号为：" + applyInfo.BudinessCode);
            
            //点数分配列表
            List<Chenxin.Lib.Business.Entity.t_Contract_PointAllotInfo> lsPointInfo = (List<Chenxin.Lib.Business.Entity.t_Contract_PointAllotInfo>)JsonHelp.Convert2Entity(strPointInfo, typeof(List<Chenxin.Lib.Business.Entity.t_Contract_PointAllotInfo>));

            //设定实体类初始值
            model = addEntity(model);

            //保存点数分配信息
            for (int i = 0; i < lsPointInfo.Count; i++)
            {
                lsPointInfo[i].RecordId = Guid.NewGuid();
                lsPointInfo[i].ContractId = model.ContractId;
                lsPointInfo[i].CreateTime = DateTime.Now;
                Chenxin.Lib.Business.DAL.t_Contract_PointAllotInfo.Add(lsPointInfo[i]);
            }

            //保存上下家客户信息
            string strOutMessage = "";
            if (!Chenxin.Lib.Business.BLL.ContractBaseInfo.AddContractCustomerInfo(model, out strOutMessage))
                return string.Format("{{success:'-1',msg:'{0}',data:''}}", Resources.Message.Global_Err_Exception + ":" + strOutMessage);

            //保存成交佣金信息
            if (!Chenxin.Lib.Business.BLL.ContractBaseInfo.AddContractCommissionInfo(model, out strOutMessage))
                return string.Format("{{success:'-1',msg:'{0}',data:''}}", Resources.Message.Global_Err_Exception + ":" + strOutMessage);

            //生成成交编号
            model.ContractCode = Chenxin.Lib.Business.BLL.ContractBaseInfo.GenerateCode(model.BargainCompanyId, model.BusinessType.Value);

            //保存成交信息
            Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.Add(model);

            if (model.BusinessType == 10 || model.BusinessType == 20)
            {
                //保存新业主信息
                Chenxin.Lib.Business.BLL.ContractBaseInfo.AddHouseNewOwnerInfo(model, out strOutMessage);
                
                //保存房源更新信息
                Chenxin.Lib.Business.BLL.ContractBaseInfo.UpdateHouseInfo(model, out strOutMessage);
            }

            //添加跟单记录
            Chenxin.Lib.House.Entity.House_TraceInfo house_TraceInfo = new Chenxin.Lib.House.Entity.House_TraceInfo();
            house_TraceInfo.TraceType = 0;
            house_TraceInfo.TraceContext = model.ConfirmEmplyee + "确认了" +
                model.BuyerUserName + "的" + (model.BusinessType == 10 ? "买卖" : "租赁") + "业绩申请。" +
                "编号：" + model.ContractCode + ";状态变为：暂缓.";

            house_TraceInfo.HouseId = model.HouseId;
            house_TraceInfo.HouseCode = model.HouseCode;
            house_TraceInfo.HouseAddress = model.HouseAddress;
            house_TraceInfo.status = 0;
            house_TraceInfo.OprDepart = model.BuyerDepartName;
            house_TraceInfo.OprDepartId = model.BuyerDepartId;
            house_TraceInfo.OprPerson = model.BuyerUserName;
            house_TraceInfo.OprPersonId = model.BuyerUserId;
            AddTrace(house_TraceInfo);

            //添加日志
            Chenxin.Lib.House.Entity.House_UserLogs userLogs = new Chenxin.Lib.House.Entity.House_UserLogs();
            userLogs.RecordId = Guid.NewGuid();
            userLogs.UserId = CurrentUserInfo.UserId;
            userLogs.UserName = CurrentUserInfo.UserName;
            userLogs.DepartId = CurrentUserInfo.DepartId;
            userLogs.DepartName = CurrentUserInfo.DepartName;
            userLogs.OperationContext = model.ConfirmEmplyee + "确认了" +
                model.BuyerUserName + "的" + (model.BusinessType == 10 ? "买卖" : "租赁") + "业绩申请。" +
                "编号：" + model.ContractCode + ";状态变为：暂缓.";
            userLogs.OprType = "确认成交编号";
            userLogs.Addtime = DateTime.Now;
            userLogs.Id = model.HouseId;
            Chenxin.Lib.House.DAL.House_UserLogs.Add(userLogs);

            Chenxin.Lib.Business.Entity.ContractApplyInfo entCAI = Chenxin.Lib.Business.DAL.ContractApplyInfo.GetModel(model.ApplyId);
            entCAI.BudinessCode = model.ContractCode;
            entCAI.ConfirmType = 1;
            entCAI.DoneDay = DateTime.Now;
            Chenxin.Lib.Business.DAL.ContractApplyInfo.Update(entCAI);

            string text = string.Empty;
            switch (applyInfo.BusinessType)
            {
                case 10:
                    text = CurrentUserInfo.UserName + "：确认买卖业绩申请。房源：[" + applyInfo.HouseCode + "]" + applyInfo.HouseAddress;
                    AddLog(text, BusinessType.BusinessTypeComboList()["OprType_M_ConfirmApply"].ToString());
                    break;
                case 20:
                    text = CurrentUserInfo.UserName + "：确认租赁业绩申请。房源：[" + applyInfo.HouseCode + "]" + applyInfo.HouseAddress;
                    AddLog(text, BusinessType.BusinessTypeComboList()["OprType_Z_ConfirmApply"].ToString());
                    break;
                case 30:
                    text = CurrentUserInfo.UserName + "：确认零散业绩申请。房源：[" + applyInfo.Community + "]" + applyInfo.HouseAddress;
                    AddLog(text, BusinessType.BusinessTypeComboList()["OprType_L_ConfirmApply"].ToString());
                    break;
                case 40:
                    text = CurrentUserInfo.UserName + "：确认其他业绩申请。业务描述：" + applyInfo.BusinessDescribe;
                    AddLog(text, BusinessType.BusinessTypeComboList()["OprType_Q_ConfirmApply"].ToString());
                    break;
            }

            return string.Format("{{success:'1',msg:'{0}',data:''}}", model.ContractCode);
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }
    
    /// <summary>
    /// 获取初始信息
    /// type为add，表示是添加主营业务
    /// type为edit，表示是编辑主营业务或者确认主营业务
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string GetInitData(HttpContext context)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        string modelId = context.Request["modelid"];

        string houseid = "";

        switch (context.Request["type"])
        {
            case "edit":

                //业绩申请实体类
                Chenxin.Lib.Business.Entity.ContractApplyInfo entInfo = Chenxin.Lib.Business.BLL.ContractApplyInfo.GetModel(new Guid(modelId));
                
                houseid = entInfo.HouseId.ToString();

                //点数业务类
                System.Data.DataSet ds = Chenxin.Lib.Business.BLL.ApplyPointAllot.GetList(string.Format("ContractId = '{0}'", modelId));

                sb.AppendFormat("applyInfo:{0},pointList:{{count:{1},{2}}}", JsonHelp.Convert2Json(entInfo), ds.Tables[0].Rows.Count, JsonHelp.Convert2Json(ds.Tables[0]));
                break;
            case "add":
                //获取相应房源信息

                houseid = modelId;

                Chenxin.Lib.House.Entity.House_BaseInfo entHouseInfo = Chenxin.Lib.House.BLL.House_BaseInfo.GetHouseInfoEntity(modelId);
                sb.AppendFormat("houseInfo:{0},userInfo:{1}", JsonHelp.Convert2Json(entHouseInfo), JsonHelp.Convert2Json(CurrentUserInfo));
                break;
        }


        //是否有钥匙
        bool hasKey = false;
        List<Chenxin.Lib.House.Entity.House_KeyReceiptionInfo> keylist = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetListArray(" HouseId='" + houseid + "'");
        if (keylist.Count > 0)
            hasKey = true;

        //是否有备案
        bool hasMarked = false;
        List<Chenxin.Lib.House.Entity.House_MarkedInfo> marklist = Chenxin.Lib.House.DAL.House_MarkedInfo.GetListArray(" HouseId='" + houseid + "'");
        if (marklist.Count > 0)
            hasMarked = true;

        sb.AppendFormat(",hasKey:{0},hasMarked:{1}", hasKey.ToString().ToLower(), hasMarked.ToString().ToLower());

        return string.Format("{{success:1,msg:'',data:{{{0}}}}}", sb.ToString());
    }
    
    /// <summary>
    /// 更新业绩申请信息
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string UpdateApplyInfo(HttpContext context)
    {
        string strRet = string.Empty;
        //业绩申请信息实体        
        string strApplyInfo = context.Request.Params["model"];
        if (strApplyInfo == null || strApplyInfo == string.Empty)
            return retExecResult(Constants.ExecResult.Error, "申请信息丢失或不存在！请联系管理员！！", "");

        //点数分配情况实体
        string strPointInfo = context.Request.Params["PointInfo"].ToString();
        if (strPointInfo == null || strPointInfo == string.Empty)
            return retExecResult(Constants.ExecResult.Error, "点数分配信息丢失或不存在！请联系管理员！！", "");

        //点数情况列表
        List<Chenxin.Lib.Business.Entity.ApplyPointAllot> lsPointInfo =
            (List<Chenxin.Lib.Business.Entity.ApplyPointAllot>)JsonHelp.Convert2Entity(strPointInfo,
                        typeof(List<Chenxin.Lib.Business.Entity.ApplyPointAllot>));

        //主营业务实体类
        Chenxin.Lib.Business.Entity.ContractApplyInfo applyInfo =
            (Chenxin.Lib.Business.Entity.ContractApplyInfo)JsonHelp.Convert2Entity(strApplyInfo,
                typeof(Chenxin.Lib.Business.Entity.ContractApplyInfo));

        //填充制限信息
        applyInfo = CompleteApplyInfo(applyInfo);

        //删除点数信息
        Chenxin.Lib.Business.BLL.ApplyPointAllot.DeleteByContractId(applyInfo.RecordId);

        //Insert点数信息
        for (int idxCnt = 0; idxCnt < lsPointInfo.Count; idxCnt++)
        {
            lsPointInfo[idxCnt].RecordId = Guid.NewGuid();
            lsPointInfo[idxCnt].ContractId = applyInfo.RecordId;
            lsPointInfo[idxCnt].CreateTime = DateTime.Now;
            lsPointInfo[idxCnt].UpdateTime = DateTime.Now;
            Chenxin.Lib.Business.BLL.ApplyPointAllot.Add(lsPointInfo[idxCnt]);
        }
        
        //Insert主营业务业绩申请信息
        Chenxin.Lib.Business.BLL.ContractApplyInfo.Update(applyInfo);

        string text = string.Empty;
        switch (applyInfo.BusinessType)
        {
            case 10:
                text = CurrentUserInfo.UserName + "：编辑买卖业绩申请。房源：[" + applyInfo.HouseCode + "]" + applyInfo.HouseAddress;
                AddLog(text, BusinessType.BusinessTypeComboList()["OprType_M_UpdApply"].ToString());
                break;
            case 20:
                text = CurrentUserInfo.UserName + "：编辑租赁业绩申请。房源：[" + applyInfo.HouseCode + "]" + applyInfo.HouseAddress;
                AddLog(text, BusinessType.BusinessTypeComboList()["OprType_Z_UpdApply"].ToString());
                break;
            case 30:
                text = CurrentUserInfo.UserName + "：编辑零散业绩申请。房源：[" + applyInfo.Community + "]" + applyInfo.HouseAddress;
                AddLog(text, BusinessType.BusinessTypeComboList()["OprType_L_UpdApply"].ToString());
                break;
            case 40:
                text = CurrentUserInfo.UserName + "：编辑其他业绩申请。业务描述：" + applyInfo.BusinessDescribe;
                AddLog(text, BusinessType.BusinessTypeComboList()["OprType_Q_UpdApply"].ToString());
                break;
        }

        strRet = retExecResult(Constants.ExecResult.Succ, Resources.Message.Msg_ResultApplySucc, "");

        return strRet;
    }
    
    /// <summary>
    /// 新增业绩申请
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string AddApplyInfo(HttpContext context)
    {
        string strRet = string.Empty;
        //业绩申请信息实体        
        string strApplyInfo = context.Request.Params["model"];
        if (strApplyInfo == null || strApplyInfo==string.Empty)
            return retExecResult(Constants.ExecResult.Error, "申请信息丢失或不存在！请联系管理员！！", "");
        
        //点数分配情况实体
        string strPointInfo = context.Request.Params["PointInfo"].ToString();
        if (strPointInfo == null || strPointInfo == string.Empty)
            return retExecResult(Constants.ExecResult.Error, "点数分配信息丢失或不存在！请联系管理员！！", "");
        
        //点数情况列表
        List<Chenxin.Lib.Business.Entity.ApplyPointAllot> lsPointInfo = 
            (List<Chenxin.Lib.Business.Entity.ApplyPointAllot>)JsonHelp.Convert2Entity(strPointInfo,
                        typeof(List<Chenxin.Lib.Business.Entity.ApplyPointAllot>));

        //主营业务实体类
        Chenxin.Lib.Business.Entity.ContractApplyInfo applyInfo =
            (Chenxin.Lib.Business.Entity.ContractApplyInfo)JsonHelp.Convert2Entity(strApplyInfo,
                typeof(Chenxin.Lib.Business.Entity.ContractApplyInfo));

        //填充制限信息
        applyInfo = CompleteApplyInfo(applyInfo);

        //Insert点数信息
        for (int idxCnt = 0; idxCnt < lsPointInfo.Count; idxCnt++)
        {
            lsPointInfo[idxCnt].RecordId = Guid.NewGuid();
            lsPointInfo[idxCnt].ContractId = applyInfo.RecordId;
            lsPointInfo[idxCnt].CreateTime = DateTime.Now;
            lsPointInfo[idxCnt].UpdateTime = DateTime.Now;
            Chenxin.Lib.Business.BLL.ApplyPointAllot.Add(lsPointInfo[idxCnt]);
        }

        //Insert主营业务业绩申请信息
        Chenxin.Lib.Business.BLL.ContractApplyInfo.Add(applyInfo);

        string text = string.Empty;
        switch (applyInfo.BusinessType)
        {
            case 10:
                text = CurrentUserInfo.UserName + "：添加买卖业绩申请。房源：[" + applyInfo.HouseCode + "]" + applyInfo.HouseAddress;
                AddLog(text, BusinessType.BusinessTypeComboList()["OprType_M_AddApply"].ToString());
                break;
            case 20:
                text = CurrentUserInfo.UserName + "：添加租赁业绩申请。房源：[" + applyInfo.HouseCode + "]" + applyInfo.HouseAddress;
                AddLog(text, BusinessType.BusinessTypeComboList()["OprType_Z_AddApply"].ToString());
                break;
            case 30:
                text = CurrentUserInfo.UserName + "：添加零散业绩申请。房源：[" + applyInfo.Community + "]" + applyInfo.HouseAddress;
                AddLog(text, BusinessType.BusinessTypeComboList()["OprType_L_AddApply"].ToString());
                break;
            case 40:
                text = CurrentUserInfo.UserName + "：添加其他业绩申请。业务描述：" + applyInfo.BusinessDescribe;
                AddLog(text, BusinessType.BusinessTypeComboList()["OprType_Q_AddApply"].ToString());
                break;
        }
        
        strRet = retExecResult(Constants.ExecResult.Succ, Resources.Message.Msg_ResultApplySucc, "");

        return strRet;
    }



    /// <summary>
    /// 初始化业绩申请对象的默认初值
    /// </summary>
    /// <param name="applyInfo"></param>
    /// <returns></returns>
    private Chenxin.Lib.Business.Entity.ContractApplyInfo CompleteApplyInfo(Chenxin.Lib.Business.Entity.ContractApplyInfo applyInfo)
    {
        if (applyInfo == null) return null;
        Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo depart = null;
        //填充下家业务城市及公司
        if (applyInfo.BuyerCompanyId == null || applyInfo.BuyerCompanyId == Guid.Empty)
        {
            depart = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(applyInfo.BuyerDepartId);
            if (depart == null) throw new Exception("获取下家部门信息失败");

            applyInfo.BuyerCompanyId = depart.CompanyId;
            applyInfo.BuyerCompanyName = depart.CompanyName;
            applyInfo.BuyerCityId = depart.CityId;
            applyInfo.BuyerCityName = depart.City;
        }

        //填充上家业务城市及公司(主营业务时有上家业务人员信息)
        if (applyInfo.BusinessType == 10 || applyInfo.BusinessType == 20)
        {
            if (applyInfo.BuyerCompanyId == null || applyInfo.BuyerCompanyId == Guid.Empty)
            {
                depart = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(applyInfo.VenderDepartId);
                if (depart == null) throw new Exception("获取上家部门信息失败");

                applyInfo.VenderCompanyId = depart.CompanyId;
                applyInfo.VenderCompanyName = depart.CompanyName;
                applyInfo.VenderCityId = depart.CityId;
                applyInfo.VenderCityName = depart.City;
            }
        }
        
        //新增数据时
        if (applyInfo.RecordId == Guid.Empty)
        {
            applyInfo.RecordId = Guid.NewGuid();

            applyInfo.CreateCityId = CurrentUserInfo.CityId;
            applyInfo.CreateCityName = CurrentUserInfo.CityName;
            applyInfo.CreateCompanyId = CurrentUserInfo.CompanyId;
            applyInfo.CreateCompanyName = CurrentUserInfo.CompanyName;
            applyInfo.CreateDepartmentId = CurrentUserInfo.DepartId;
            applyInfo.CreateDepartmentName = CurrentUserInfo.DepartName;
            applyInfo.CreateUserId = CurrentUserInfo.UserId;
            applyInfo.CreateUserName = CurrentUserInfo.UserName;
            applyInfo.CreateTime = applyInfo.ApplicationDay = DateTime.Now;

            applyInfo.ConfirmType = 0;
            applyInfo.Status = 1;
        }
        else//数据更新时
        {
            //源数据信息
            Chenxin.Lib.Business.Entity.ContractApplyInfo oldApplyInfo = ContractApplyInfo.GetModel(applyInfo.RecordId);

            if (oldApplyInfo == null) throw new Exception("申请信息丢失！请联系管理员！");
            applyInfo.CreateCityId = oldApplyInfo.CreateCityId;
            applyInfo.CreateCityName = oldApplyInfo.CreateCityName;
            applyInfo.CreateCompanyId = oldApplyInfo.CreateCompanyId;
            applyInfo.CreateCompanyName = oldApplyInfo.CreateCompanyName;
            applyInfo.CreateDepartmentId = oldApplyInfo.CreateDepartmentId;
            applyInfo.CreateDepartmentName = oldApplyInfo.CreateDepartmentName;
            applyInfo.CreateUserId = oldApplyInfo.CreateUserId;
            applyInfo.CreateUserName = oldApplyInfo.CreateUserName;
            applyInfo.CreateTime = oldApplyInfo.CreateTime;

            applyInfo.Status = oldApplyInfo.Status;
            applyInfo.DoneDay = oldApplyInfo.DoneDay;
            applyInfo.BudinessCode = oldApplyInfo.BudinessCode;
            applyInfo.ConfirmType = oldApplyInfo.ConfirmType;

            //房源固定信息
            applyInfo.VenderCityId = oldApplyInfo.VenderCityId;
            applyInfo.VenderCompanyId = oldApplyInfo.VenderCompanyId;
            applyInfo.VenderCompanyName = oldApplyInfo.VenderCompanyName;
            applyInfo.VenderDepartId = oldApplyInfo.VenderDepartId;
            applyInfo.VenderUserId = oldApplyInfo.VenderUserId;

            applyInfo.CommunityId = oldApplyInfo.CommunityId;
            applyInfo.CommunityAddress = oldApplyInfo.CommunityAddress;
            applyInfo.Community = oldApplyInfo.Community;
            applyInfo.CurrentFloor = oldApplyInfo.CurrentFloor;
            applyInfo.TotalFloor = oldApplyInfo.TotalFloor;
            applyInfo.BuildingType = oldApplyInfo.BuildingType;
            applyInfo.HouseUse = oldApplyInfo.HouseUse;
            applyInfo.HouseType = oldApplyInfo.HouseType;
        }

        applyInfo.UpdateCityId = CurrentUserInfo.CityId;
        applyInfo.UpdateCityName = CurrentUserInfo.CityName;
        applyInfo.UpdateCompanyId = CurrentUserInfo.CompanyId;
        applyInfo.UpdateCompanyName = CurrentUserInfo.CompanyName;
        applyInfo.UpdateDepartmentId = CurrentUserInfo.DepartId;
        applyInfo.UpdateDepartmentName = CurrentUserInfo.DepartName;
        applyInfo.UpdateUserId = CurrentUserInfo.UserId;
        applyInfo.UpdateUserName = CurrentUserInfo.UserName;
        applyInfo.UpdateTime = DateTime.Now;

        if (applyInfo.BusinessType != 10)
            applyInfo.FixDiscount = 0;

        return applyInfo;
    }

    /// <summary>
    /// 获取备案列表
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string getMarkList(HttpContext context)
    {
        try
        {
            string strRet = string.Empty;
            System.Data.DataSet ds = Chenxin.Lib.House.DAL.House_MarkedInfo.GetList(" HouseId='" + context.Request.Params["houseid"] + "' ");
            strRet = string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0]));
            return strRet;
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }

    /// <summary>
    /// 获取钥匙列表
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string getKeyList(HttpContext context)
    {
        try
        {
            string strRet = string.Empty;
            System.Data.DataSet ds = Chenxin.Lib.House.DAL.House_KeyReceiptionInfo.GetList(" HouseId='" + context.Request.Params["houseid"] + "'");
            strRet = string.Format("{{success:1,msg:'',data:{{count:{0},{1}}}}}", ds.Tables[0].Rows.Count, Chenxin.Lib.Utility.JsonHelp.Convert2Json(ds.Tables[0]));
            return strRet;
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'{0}：{1}',data:''}}", Resources.Message.Global_Err_Exception, ex.Message);
        }
    }

    /// <summary>
    /// 获取指定部门的区经高经店长等。。。
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    private string getParents(HttpContext context)
    {
        //StringBuilder strRet = new StringBuilder();
        System.Text.StringBuilder strIDs = new System.Text.StringBuilder();

        ContractApplyInfo bllConApp = new ContractApplyInfo();

        System.Data.DataSet ds = ContractApplyInfo.GetRoleByDepartId(new Guid(context.Request.Params["modelid"].ToString()));

        if (ds.Tables[0].Rows.Count > 0)
        {
            strIDs.Append(ConvertToJsonEx("isroleb", "DeparterManager", ds));
            strIDs.Append(ConvertToJsonEx("isrolec", "Manger", ds));
            strIDs.Append(ConvertToJsonEx("isroled", "RegionManger", ds));
            strIDs.Append(ConvertToJsonEx("isrolee", "Majordomo", ds));
            strIDs.AppendFormat("DepartId:'{0}'", context.Request["modelid"]);
        }
        
        return string.Format("{{success:1,msg:'',data:{{{0}}}}}", strIDs.ToString());
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="type"></param>
    /// <param name="flag"></param>
    /// <param name="ds"></param>
    /// <returns></returns>
    private string ConvertToJsonEx(string type, string flag, System.Data.DataSet ds)
    {
        System.Data.DataRow[] dr = ds.Tables[0].Select("type='" + type + "'");

        if (dr.Length > 0)
        {
            return string.Format("{0}Id:'{1}',{0}Name:'{2}',", flag, dr[0]["userid"], dr[0]["username"]);
        }
        return "";
    }

    //*******************************************
    //功能概要       ：获取标准佣金
    //参数説明       ：context 请求上下文
    //返回值説明     ：标准佣金
    //功能詳細       ：获取标准佣金
    //作成者         ：he.jifeng
    //作成日         ：2010-08-16
    //*******************************************
    private string getStandardCommission(HttpContext context)
    {
        string strRet = string.Empty;
        //交易类型
        string strType = context.Request.Params["BusinessType"];
        //房屋性质
        string strProperty = context.Request.Params["HouseProperty"];
        //合同标的
        string strBargainPrice = context.Request.Params["BargainPrice"];

        if (strType == null || strProperty == null || strBargainPrice == null)
        {
            strRet = retExecResult(Constants.ExecResult.Error, Resources.Message.Err_UrlError, "");
        }
        else
        {
            System.Text.StringBuilder strRate = new System.Text.StringBuilder();
            //标准佣金业务类
            CommissionRate bllRate = new CommissionRate();
            //检索条件
            Dictionary<string, string> dicParams = new Dictionary<string, string>();
            dicParams.Add("CompanyId", CurrentUserInfo.CompanyId.ToString());
            dicParams.Add("BusinessType", strType);
            dicParams.Add("HouseProperty", strProperty);

            List<Chenxin.Lib.Business.Entity.CommissionRate> lsRate = bllRate.GetListByParams(dicParams);

            if (lsRate.Count == 0)
            {
                strRet = retExecResult(Constants.ExecResult.Error, Resources.Message.Err_DictionaryError, "");
            }
            else
            {
                Decimal dPrice = Convert.ToDecimal(context.Request.Params["BargainPrice"]);
                strRate.Append("{");
                strRate.Append("success:'1',");
                strRate.Append("msg:'',");
                strRate.AppendFormat("data:{{VCommission:{0},BCommission:{1}}}", Math.Round(lsRate[0].VStandardRate.Value * dPrice, 2), Math.Round(lsRate[0].BStandardRate.Value * dPrice, 2));
                strRate.Append("}");

                strRet = strRate.ToString();
            }

        }
        return strRet;
    }


    //*******************************************
    //功能概要       ：完善业绩确认记录
    //参数説明       ：context 请求上下文
    //返回值説明     ：程序处理信息提示
    //功能詳細       ：查询业绩申请信息
    //作成者         ：kimi
    //作成日         ：2010-10-29
    //修改者         ：
    //修改日         ：
    //*******************************************
    private Chenxin.Lib.Business.Entity.t_Contract_BaseInfo addEntity(Chenxin.Lib.Business.Entity.t_Contract_BaseInfo model)
    {
        if (model.ContractId == null || model.ContractId == Guid.Empty)
            return completeNewEnity(model);
        else
            return completeUpdateEnity(model);
    }

    private Chenxin.Lib.Business.Entity.t_Contract_BaseInfo completeUpdateEnity(Chenxin.Lib.Business.Entity.t_Contract_BaseInfo model)
    {
        Chenxin.Lib.Business.Entity.t_Contract_BaseInfo oldModel = Chenxin.Lib.Business.DAL.t_Contract_BaseInfo.GetModel(model.ContractId);
        if (oldModel == null)
            throw new Exception("成交记录信息丢失，请联系管理员！！");
        
        //申请ID
        oldModel.ContractDate = model.ContractDate;
        oldModel.BusinessDescribe = model.BusinessDescribe;
        oldModel.HouseProperty = model.HouseProperty;
        oldModel.BusinessType = model.BusinessType;
        oldModel.BargainType = model.BargainType;
        oldModel.BargainPrice = model.BargainPrice;
        oldModel.Area = model.Area;
        oldModel.BargainUnitPrice = (model.Area>0) ? model.BargainPrice / model.Area:0;
        oldModel.HouseAddress = model.HouseAddress;
        oldModel.Region = model.Region;
        oldModel.Block = model.Block;
        oldModel.BuildingType = model.BuildingType;
        oldModel.HouseUse = model.HouseUse;
        oldModel.CurrentFloor = model.CurrentFloor;
        oldModel.TotalFloor = model.TotalFloor;
        oldModel.PropertyCode = model.PropertyCode;
        oldModel.CommunityId = model.CommunityId;
        oldModel.Community = model.Community;
        
        oldModel.VenderName = model.VenderName;
        oldModel.VenderNo = model.VenderNo;
        oldModel.VenderPhone = model.VenderPhone;
        oldModel.VenderMobile = model.VenderMobile;

        oldModel.BuyerDepartId = model.BuyerDepartId;
        oldModel.BuyerDepartName = model.BuyerDepartName;
        oldModel.BuyerUserId = model.BuyerUserId;
        oldModel.BuyerUserName = model.BuyerUserName;

        oldModel.BuyerName = model.BuyerName;
        oldModel.BuyerNo = model.BuyerNo;
        oldModel.BuyerPhone = model.BuyerPhone;
        oldModel.BuyerMobile = model.BuyerMobile;

        oldModel.PointRemark = model.PointRemark;
        oldModel.CustomerSource = model.CustomerSource;

        oldModel.VStanCommision = (model.VStanCommision.HasValue == false) ? 0 : model.VStanCommision;
        oldModel.BStanCommision = (model.BStanCommision.HasValue == false) ? 0 : model.BStanCommision;
        oldModel.VRealCommision = (model.VRealCommision.HasValue == false) ? 0 : model.VRealCommision;
        oldModel.BRealCommision = (model.BRealCommision.HasValue == false) ? 0 : model.BRealCommision;
        oldModel.VCommision = (model.VCommision.HasValue == false) ? 0 : model.VCommision;
        oldModel.BCommision = (model.BCommision.HasValue == false) ? 0 : model.BCommision;
        oldModel.VConsulting = (model.VConsulting.HasValue == false) ? 0 : model.VConsulting;
        oldModel.BConsulting = (model.BConsulting.HasValue == false) ? 0 : model.BConsulting;

        oldModel.FixDiscount = model.FixDiscount;
        oldModel.DiscountRate = model.DiscountRate;

        oldModel.ContractDepartmentId = model.ContractDepartmentId;
        oldModel.ContractDepartmentName = model.ContractDepartmentName;
        oldModel.ContractUserId = model.ContractUserId;
        oldModel.ContractUserName = model.ContractUserName;

        oldModel.UpdateDepartmentId = CurrentUserInfo.DepartId;
        oldModel.UpdateDepartmentName = CurrentUserInfo.DepartName;
        oldModel.UpdateUserId = CurrentUserInfo.UserId;
        oldModel.UpdateUserName = CurrentUserInfo.UserName;
        oldModel.UpdateTime = DateTime.Now;
        
        Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo departs = null;

        if (oldModel.BuyerDepartId == null || oldModel.BuyerDepartId == Guid.Empty)
        {
            throw new Exception("下家部门标识丢失或不存在");
        }

        departs = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(oldModel.BuyerDepartId);
        if (departs == null) throw new Exception("下家部门信息丢失");

        oldModel.BuyerCityId = departs.CityId;
        oldModel.BuyerCityName = departs.City;
        oldModel.BuyerCompanyId = departs.CompanyId;
        oldModel.BuyerCompanyName = departs.CompanyName;

        if (oldModel.ContractDepartmentId == null || oldModel.ContractDepartmentId == Guid.Empty) throw new Exception("签约部门信息丢失");
        departs = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(model.ContractDepartmentId);
        if (departs == null) throw new Exception("签约部门信息丢失");

        oldModel.ContractCityId = departs.CityId;
        oldModel.ContractCityName = departs.City;
        oldModel.ContractCompanyId = departs.CompanyId;
        oldModel.ContractCompanyName = departs.CompanyName;

        return oldModel;
    }
    

    private Chenxin.Lib.Business.Entity.t_Contract_BaseInfo completeNewEnity(Chenxin.Lib.Business.Entity.t_Contract_BaseInfo model)
    {
        Chenxin.Lib.Business.Entity.ContractApplyInfo info = Chenxin.Lib.Business.DAL.ContractApplyInfo.GetModel(model.ApplyId);
        Chenxin.Lib.House.Entity.House_BaseInfo houseinfo = Chenxin.Lib.House.DAL.House_BaseInfo.GetModel(info.HouseId);

        if (houseinfo != null)
        {
            model.CommunityId = houseinfo.CommunityId;
            model.Community = houseinfo.Community;
        }
        else
        {
            model.CommunityId = info.CommunityId;
            model.Community = info.Community;            
        }
        model.RateDate = DateTime.Now;
        model.DiscountRate = 1;
        model.VSTDiscount = 0;
        model.BSTDiscount = 0;
        
        //合同ID
        model.ContractId = Guid.NewGuid();
        //申请ID
        model.ApplyId = model.ApplyId;
        //合同编号

        if (model.Area != 0) model.BargainUnitPrice = model.BargainPrice / model.Area;
        model.HouseId = info.HouseId;
        model.HouseCode = info.HouseCode;
        model.CommunityAddress = info.CommunityAddress;
        model.HouseUse = info.HouseUse;
        model.HouseType = info.HouseType;
        Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo departs = null;
        if (model.BusinessType == 10 || model.BusinessType == 20)
        {
            if (model.VenderDepartId == null || model.VenderDepartId == Guid.Empty)
            {
                throw new Exception("上家部门标识丢失或不存在");
            }
            departs = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(model.VenderDepartId);
            if (departs == null) throw new Exception("上家部门信息丢失");

            model.VenderCityId = departs.CityId;
            model.VenderCityName = departs.City;
            model.VenderCompanyId = departs.CompanyId;
            model.VenderCompanyName = departs.CompanyName;
        }

        if (model.BuyerDepartId == null || model.BuyerDepartId == Guid.Empty)
        {
            throw new Exception("下家部门标识丢失或不存在");
        }

        departs = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(model.BuyerDepartId);
        if (departs == null) throw new Exception("下家部门信息丢失");

        model.BuyerCityId = departs.CityId;
        model.BuyerCityName = departs.City;
        model.BuyerCompanyId = departs.CompanyId;
        model.BuyerCompanyName = departs.CompanyName;

        model.AppEmployeeId = info.CreateUserId;
        model.AppEmployee = info.CreateUserName;
        model.AppDepartId = info.CreateDepartmentId;
        model.AppDepart = info.CreateDepartmentName;
        model.AppCompanyId = info.CreateCompanyId;
        model.AppCompany = info.CreateCompanyName;
        model.AppCityId = info.CreateCityId;
        model.AppCity = info.CreateCityName;

        model.ConfirmEmplyeeId = CurrentUserInfo.UserId;
        model.ConfirmEmplyee = CurrentUserInfo.UserName;
        model.ConfirmDepartId = CurrentUserInfo.DepartId;
        model.ConfirmDepart = CurrentUserInfo.DepartName;
        model.ConfirmCompanyId = CurrentUserInfo.CompanyId;
        model.ConfirmCompany = CurrentUserInfo.CompanyName;
        model.ConfirmCityId = CurrentUserInfo.CityId;
        model.ConfirmCity = CurrentUserInfo.CityName;
        model.AddTime = DateTime.Now;

        model.UpdateDepartmentId = CurrentUserInfo.DepartId;
        model.UpdateDepartmentName = CurrentUserInfo.DepartName;
        model.UpdateUserId = CurrentUserInfo.UserId;
        model.UpdateUserName = CurrentUserInfo.UserName;
        model.UpdateTime = DateTime.Now;

        model.bArchivement = false;
        model.LockStatus = 255;
        model.Status = 1;

        if (model.ContractDepartmentId == null || model.ContractDepartmentId == Guid.Empty) throw new Exception("签约部门信息丢失");
        departs = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(model.ContractDepartmentId);
        if (departs == null) throw new Exception("签约部门信息丢失");

        model.ContractCityId = departs.CityId;
        model.ContractCityName = departs.City;
        model.ContractCompanyId = departs.CompanyId;
        model.ContractCompanyName = departs.CompanyName;
        model.VenderId = Guid.NewGuid();
        model.BuyerId = Guid.NewGuid();

        return model;
    }
}